﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ERPStore.Web.Extensions;

using CloudSoft.Extensions;

using ERPStore.Extensions;

using ERPStore.Web.Html;

namespace ERPStore.Coupons.Services.Providers
{
	public class GlobalDiscountProvider : CouponProviderBase
	{

		public override string Description
		{
			get { return "Remise globale sur le panier"; }
		}

		public override IList<ERPStore.Models.BrokenRule> ValidateUse(ERPStore.Models.OrderCart cart, ERPStore.Models.UserPrincipal principal)
		{
			var brokenRules = base.ValidateUse(cart, principal) ?? new List<ERPStore.Models.BrokenRule>();

			if (cart.DiscountList.Cast<Models.CartDiscount>().Any(i => i.CouponSource.ProviderName == this.Name))
			{
				brokenRules.AddBrokenRule("couponcode", "Un coupon de type remise globale est déjà appliqué");
			}

			return brokenRules;
		}

		public override void ApplyDiscountTo(Models.CartDiscount cartDiscount, ERPStore.Models.OrderCart cart, ERPStore.Models.UserPrincipal principal)
		{
			if (!Coupon.DiscountPercent.HasValue)
			{
				return;
			}
			cartDiscount.DiscountReason = Coupon.Description;
			var discount = new ERPStore.Models.Price(cart.TotalWithoutDiscountByItem * Convert.ToDecimal(Coupon.DiscountPercent), cart.GetShippingTaxRate(principal) / 100d);
			cartDiscount.Discount = discount.Value;
			cartDiscount.DiscountWithTax = discount.ValueWithTax;
			cartDiscount.Code = Coupon.Code;
		}


	}
}
